package com.hxg.bl.controller;

import com.github.pagehelper.PageInfo;
import com.hxg.bl.bean.StoreBean;
import com.hxg.bl.dao.jpa.StoreBeanJpa;
import com.hxg.bl.service.StoreService;
import com.hxg.bl.vo.SearchVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;

@Controller
@RequestMapping("/store")
public class StoreController {

    @Autowired
    private StoreBeanJpa storeBeanJpa;

    @Autowired
    private StoreService storeService;

    @RequestMapping("/listStore")
    public String listStore() {
        return "bl/store/store_list";
    }

    @RequestMapping("/listStoreByParams")
    @ResponseBody
    public PageInfo<StoreBean> listStoreByParams(
            @RequestParam(value = "pn", defaultValue = "1") Integer pn,
            @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize,
            SearchVo searchVo
    ) {
        return storeService.listStoreByParams(pn, pageSize, searchVo);
    }

    @RequestMapping("/addOrEditStore")
    public String addOrEditStore(
            Map<String, Object> map,
            @RequestParam(value = "id", defaultValue = "") Long id
    ) {

        StoreBean storeBean = new StoreBean();
        if (null != id && id > 0) {
            storeBean = storeBeanJpa.getOne(id);
        }

        map.put("storeBean", storeBean);

        return "bl/store/store_add_or_edit";
    }

    @RequestMapping("/saveAndFlushStore")
    @ResponseBody
    public Map<String, Object> saveAndFlushStore(
            StoreBean storeBean
    ) {
        Map<String, Object> jsonMap = new HashMap<>();

        try {
            storeService.saveAndFlushStore(storeBean);
            jsonMap.put("flag", true);
        } catch (Exception e) {
            e.printStackTrace();
            jsonMap.put("flag", false);
            jsonMap.put("errorMsg", e.getMessage());
        }

        return jsonMap;
    }

    @RequestMapping("/batchDelStore")
    @ResponseBody
    public Map<String, Object> batchDelStore(
            @RequestParam("idList") String idList
    ) {
        Map<String, Object> jsonMap = new HashMap<>();

        try {
            storeService.batchDelStore(
                    Arrays.asList(idList.split(",")).stream()
                            .map(s -> Long.parseLong(s))
                            .collect(Collectors.toList())
            );
            jsonMap.put("flag", true);
        } catch (Exception e) {
            e.printStackTrace();
            jsonMap.put("flag", false);
            jsonMap.put("errorMsg", e.getMessage());
        }

        return jsonMap;
    }

}
